package servlet;

import java.io.IOException;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.omg.CORBA.NameValuePair;

import com.sun.xml.internal.messaging.saaj.packaging.mime.Header;

import sun.net.www.http.HttpClient;

/**
 * Servlet implementation class MessageServlet
 */
@WebServlet("/MessageServlet")
public class MessageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MessageServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
		String phone=request.getParameter("phone");
        response.setCharacterEncoding("UTF-8");
        //获取验证码
        String code=getCode();
        request.getSession().setAttribute("code", code);
		//发送短信
       sendMsg(phone,code);
        
        response.getWriter().write("true");
        response.flushBuffer();
	}

	private String getCode() {
		// TODO Auto-generated method stub
		Random rand=new Random();
		String code="";
		for(int i=0;i<4;i++){
			code+=rand.nextInt(10);
		}
		System.out.println(code);
		return code;
	}

	private void sendMsg(String phone, String code) {
		// TODO Auto-generated mlethod stub
		HttpClient client = new HttpClient(); 
		PostMethod post = new PostMethod("http://utf8.sms.webchinese.cn");//发送http请求
		post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
		NameValuePair[] data ={ new NameValuePair()		};
		post.setRequestBody(data);
		client.executeMethod(post);
		Header[] headers = post.getResponseHeaders();
		int statusCode = post.getStatusCode();
		System.out.println("statusCode:"+statusCode);
		for(Header h:headers){
			 System.out.println("---"+h.toString());
		}
		String result=new String(post.getResponseBodyAsString().getBytes("utf8"));
		System.out.println(result);//打印返回消息状态
		post.releaseConnection();
	}

}
